package com.huluobo.a2112mvvmdouyindemo.like;


import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.huluobo.a2112mvvmdouyindemo.R;
import com.huluobo.a2112mvvmdouyindemo.adapter.LikeAdapter;
import com.huluobo.a2112mvvmdouyindemo.databinding.FragmentLikeBinding;
import com.huluobo.mvvm_base.bean.LikeBeanResult;
import com.huluobo.mvvm_base.bean.LikeVideoBeanResult;
import com.huluobo.mvvm_base.view.BaseMVVMFragment;

import java.util.ArrayList;
import java.util.List;

public class LikeFragment extends BaseMVVMFragment<FragmentLikeBinding, LikeViewModel> {

    private List<LikeVideoBeanResult.LikeVideoBean> likeVideoBeanList = new ArrayList<>();
    private LikeAdapter likeAdapter;

    private int position;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_like;
    }

    @Override
    protected void initData() {
        viewModel.getLikeVideoList();

        viewModel.success.observe(this, likeVideoBeanResult -> {
            if (likeVideoBeanResult.getCode() == 200) {
                likeVideoBeanList.clear();
                likeVideoBeanList.addAll(likeVideoBeanResult.getData());
                likeAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(likeVideoBeanResult.getMessage());
            }
        });

        viewModel.failed.observe(this, s -> {
            Log.i("TagA", "likeFailed:" + s);
        });

        viewModel.cancelLikeSuccess.observe(this, likeBeanResult -> {
            ToastUtils.showLong(likeBeanResult.getMessage());
            likeVideoBeanList.remove(position);
            likeAdapter.notifyDataSetChanged();
        });


        viewModel.cancelLikeFailed.observe(this, s -> {
            Log.i("TagA", "取消点赞失败:" + s);
        });
    }

    @Override
    protected void initView() {
        dataBinding.likeRv.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        likeAdapter = new LikeAdapter(likeVideoBeanList);
        dataBinding.likeRv.setAdapter(likeAdapter);

        likeAdapter.addChildClickViewIds(R.id.item_like_delete_btn);

        likeAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.item_like_delete_btn) {
                viewModel.cancelLike(likeVideoBeanList.get(position).getId());
                this.position = position;
            }
        });
    }

    @Override
    protected Class<LikeViewModel> getViewModel() {
        return LikeViewModel.class;
    }
}